<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :append-to-body="true"
      width="600px"
      @close="resetForm('form')"
    >
      <div>
        <el-form ref="form" :rules="rules" :model="form" label-width="120px">
          <el-form-item label="文件夹名称" prop="oldName">
            <el-input v-model.trim="form.oldName"></el-input>
          </el-form-item>
          <el-form-item label="资源权限" prop="isPublic">
            <el-radio-group v-model="form.isPublic">
              <el-radio label="1">公开</el-radio>
              <el-radio label="2">不公开</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      title: '新建文件夹',
      dialogVisible: false,
      form: {
        pid: '0',
        category: '1',
        oldName: '',
        isPublic: '1',
      },
      rules: {
        oldName: [
          { required: true, message: '请输入文件夹名称', trigger: 'blur' },
        ],
        isPublic: [
          { required: true, message: '请选择资源权限', trigger: 'change' },
        ],
      },
    }
  },
  mounted() {
    this.$bus.$on('createFolder', this.init)
    this.$bus.$on('openFolder', (v) => {
      this.form.pid = v ? v.id : '0'
    })
  },
  beforeDestroy() {
    this.$bus.$off('createFolder')
    this.$bus.$off('openFolder')
  },
  methods: {
    //显示弹窗
    init(row) {
      if (row) {
        this.form = { ...this.form, ...row }
        this.$set(this.form, 'id', row.id)
      } else {
        this.form = this.$options.data().form
        this.$delete(this.form, 'id')
      }
      this.title = row ? '编辑文件夹' : '新建文件夹'
      this.dialogVisible = true
    },
    //提交
    submitForm(form) {
      this.$refs[form].validate(async (valid) => {
        if (valid) {
          if (this.title == '新建文件夹') {
            this.form.pid = this.$store.getters.netPid
          }
          let dispatchType =
            this.title == '新建文件夹'
              ? 'createDirTbNetDisk'
              : 'updateDirTbNetDisk'
          await this.$store.dispatch(dispatchType, this.form)
          this.done()
        }
      })
    },
    done() {
      this.dialogVisible = false
      this.$bus.$emit('refreshTbNetDiskList')
      this.successMsg('操作成功')
    },
    //重置表单
    resetForm(form) {
      this.$refs[form].resetFields()
    },
  },
}
</script>